"""
模板管理模块
负责生成各种项目文件的模板内容
"""

from typing import Dict, Any, List
from jinja2 import Template


class TemplateManager:
    """模板管理器"""
    
    def __init__(self):
        """初始化模板管理器"""
        self.templates = {}
    
    def get_pyproject_template(self, config: Any) -> str:
        """获取pyproject.toml模板"""
        template_str = '''[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "{{ project_name }}"
description = "{{ description }}"
dynamic = ["version"]
readme = "README.md"
license = "{{ license }}"
authors = [
    { name = "{{ author }}", email = "{{ email }}" }
]
requires-python = "{{ python_version }}"
dependencies = [
{% for dep in dependencies %}
    "{{ dep }}",
{% endfor %}
]

[project.optional-dependencies]
dev = [
{% for dep in dev_dependencies %}
    "{{ dep }}",
{% endfor %}
]

{% if project_type == 'fastmcp' %}
[project.scripts]
{{ project_name_snake }} = "main:main"
{% endif %}

[tool.hatch.version]
path = "{{ source_dir }}/__init__.py"

[tool.hatch.build.targets.wheel]
packages = ["{{ source_dir }}"]

[tool.black]
line-length = 88
target-version = ['py313']

[tool.ruff]
target-version = "py313"
line-length = 88
select = ["E", "W", "F", "I", "B", "C4", "UP"]

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = ["--cov={{ source_dir }}"]'''
        
        template = Template(template_str)
        return template.render(config.get_template_context())
    
    def get_gitignore_template(self) -> str:
        """获取.gitignore模板"""
        return '''__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
*.log
.ipynb_checkpoints
.python-version
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
.mypy_cache/
.dmypy.json
dmypy.json
.vscode/
.idea/
*.swp
*.swo
*~
.DS_Store
Thumbs.db
logs/
temp/
*.tmp'''
    
    def get_env_template(self) -> str:
        """获取.env.example模板"""
        return '''# Environment variables template
# Copy this file to .env and fill in your values

APP_NAME=my-app
APP_VERSION=0.1.0
DEBUG=True
LOG_LEVEL=INFO
HOST=0.0.0.0
PORT=8000'''
    
    def get_docker_compose_template(self, config: Any) -> str:
        """获取docker-compose.yml模板"""
        return f'''version: '3.8'

services:
  {config.project_name.replace("-", "_")}:
    build: .
    container_name: {config.project_name}
    ports:
      - "8000:8000"
    volumes:
      - ./logs:/app/logs'''
    
    def get_dockerfile_template(self, config: Any) -> str:
        """获取Dockerfile模板"""
        return '''FROM registry.cn-shenzhen.aliyuncs.com/clarkchang/python:3.13.7-slim

ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
ENV PYTHONPATH=/app

WORKDIR /app

# 使用阿里云镜像源安装uv，解决超时问题
RUN pip install -i https://mirrors.aliyun.com/pypi/simple/ uv

COPY pyproject.toml README.md ./
# 安装依赖，使用阿里云镜像源
RUN uv sync --index-url https://mirrors.aliyun.com/pypi/simple/ --frozen || uv pip compile --index-url https://mirrors.aliyun.com/pypi/simple/ pyproject.toml -o requirements.txt && uv pip install --index-url https://mirrors.aliyun.com/pypi/simple/ -r requirements.txt

COPY . .
RUN mkdir -p logs

EXPOSE 8000

CMD ["uv", "run", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]'''
    

    
    def get_fastapi_main_template(self, config: Any) -> str:
        """获取FastAPI主文件模板"""
        template_str = '''"""{{ project_name_title }} - FastAPI Application"""

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from loguru import logger
import uvicorn

from config.sys_config import get_settings
from app.api.router import api_router

settings = get_settings()

app = FastAPI(
    title="{{ project_name_title }}",
    description="{{ description }}",
    version="{{ version }}",
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(api_router, prefix="/api")

@app.get("/")
async def root():
    return {"message": "Welcome to {{ project_name_title }}"}

@app.get("/health")
async def health_check():
    return {"status": "healthy", "version": "{{ version }}"}

if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host=settings.HOST,
        port=settings.PORT,
        reload=settings.DEBUG,
    )'''
        
        template = Template(template_str)
        return template.render(config.get_template_context())
    
    def get_fastapi_router_template(self) -> str:
        """获取FastAPI路由模板"""
        return '''"""API路由模块"""

from fastapi import APIRouter
from typing import Dict, Any

api_router = APIRouter()

@api_router.get("/health")
async def health_check():
    return {"status": "healthy", "message": "API is running"}

@api_router.get("/")
async def api_root():
    return {"message": "Welcome to the API"}'''
    
    def get_fastapi_config_template(self) -> str:
        """获取FastAPI配置模板"""
        return '''"""应用配置模块"""

from functools import lru_cache
from pydantic_settings import BaseSettings
from pydantic import Field

class Settings(BaseSettings):
    APP_NAME: str = Field(default="FastAPI App")
    VERSION: str = Field(default="0.1.0")
    DEBUG: bool = Field(default=True)
    HOST: str = Field(default="0.0.0.0")
    PORT: int = Field(default=8000)
    LOG_LEVEL: str = Field(default="INFO")
    
    class Config:
        env_file = ".env"

@lru_cache()
def get_settings() -> Settings:
    return Settings()'''
    
    def get_logging_setup_template(self) -> str:
        """获取日志设置模板"""
        return '''"""日志配置模块"""

import sys
from pathlib import Path
from loguru import logger

def setup_logging(log_level: str = "INFO", log_file: str = "logs/app.log"):
    logger.remove()
    
    log_path = Path(log_file)
    log_path.parent.mkdir(parents=True, exist_ok=True)
    
    logger.add(
        sys.stdout,
        level=log_level,
        format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | {message}",
        colorize=True,
    )
    
    logger.add(
        log_file,
        level=log_level,
        format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {message}",
        rotation="10 MB",
        retention="30 days",
    )'''
    
    def get_pydantic_models_template(self) -> str:
        """获取Pydantic模型模板"""
        return '''"""数据模型模块"""

from typing import Optional, Dict, Any
from pydantic import BaseModel, Field
from datetime import datetime

class BaseResponse(BaseModel):
    message: str = Field(..., description="响应消息")
    timestamp: datetime = Field(default_factory=datetime.now)

class HealthResponse(BaseResponse):
    status: str = Field(..., description="健康状态")
    version: Optional[str] = Field(None, description="版本号")

class MessageResponse(BaseResponse):
    data: Optional[Dict[str, Any]] = Field(None, description="响应数据")'''

    def get_utils_template(self) -> str:
        """获取工具函数模板"""
        return '''"""工具函数模块"""

import secrets
import string
from datetime import datetime, timezone
from typing import Any
import json

def generate_random_string(length: int = 32) -> str:
    alphabet = string.ascii_letters + string.digits
    return ''.join(secrets.choice(alphabet) for _ in range(length))

def get_current_timestamp() -> datetime:
    return datetime.now(timezone.utc)

def safe_json_loads(json_str: str, default: Any = None) -> Any:
    try:
        return json.loads(json_str)
    except (json.JSONDecodeError, TypeError):
        return default'''
    
    def get_example_service_template(self) -> str:
        """获取示例服务模板"""
        return '''"""示例服务模块"""

from typing import Dict, Any, List
from loguru import logger

class ExampleService:
    def __init__(self):
        self.logger = logger
    
    async def get_example_data(self) -> Dict[str, Any]:
        self.logger.info("获取示例数据")
        return {
            "id": 1,
            "name": "示例数据",
            "description": "这是一个示例数据",
            "status": "active"
        }

example_service = ExampleService()'''
    
    def get_fastmcp_main_template(self, config: Any) -> str:
        """获取FastMCP主文件模板"""
        template_str = '''"""{{ project_name_title }} - FastMCP Server"""

import asyncio
from loguru import logger
from fastmcp import FastMCP

from app.mcp.server import setup_server
from app.tools.example_tools import get_tools
from app.resources.example_resources import get_resources

def main():
    """主函数"""
    logger.info("启动{{ project_name_title }} MCP Server")
    
    # 创建MCP服务器
    server = setup_server()
    
    # 注册工具
    tools = get_tools()
    for tool in tools:
        server.add_tool(tool)
    
    # 注册资源
    resources = get_resources()
    for resource in resources:
        server.add_resource(resource)
    
    # 运行服务器
    asyncio.run(server.run())

if __name__ == "__main__":
    main()'''
        
        template = Template(template_str)
        return template.render(config.get_template_context())
    
    def get_fastmcp_server_template(self) -> str:
        """获取FastMCP服务器模板"""
        return '''"""FastMCP服务器配置"""

from fastmcp import FastMCP
from loguru import logger

def setup_server() -> FastMCP:
    """设置MCP服务器"""
    logger.info("初始化MCP服务器")
    
    server = FastMCP(
        name="example-mcp-server",
        version="1.0.0",
        description="示例MCP服务器"
    )
    
    return server'''
    
    def get_fastmcp_tools_template(self) -> str:
        """获取FastMCP工具模板"""
        return '''"""FastMCP工具示例"""

from typing import List
from fastmcp.tools import Tool
from loguru import logger

def hello_tool(name: str = "World") -> str:
    """问候工具"""
    logger.info(f"执行问候工具: {name}")
    return f"Hello, {name}!"

def calculate_tool(a: float, b: float, operation: str = "add") -> float:
    """计算工具"""
    logger.info(f"执行计算: {a} {operation} {b}")
    
    if operation == "add":
        return a + b
    elif operation == "subtract":
        return a - b
    elif operation == "multiply":
        return a * b
    elif operation == "divide":
        if b == 0:
            raise ValueError("除数不能为零")
        return a / b
    else:
        raise ValueError(f"不支持的操作: {operation}")

def get_tools() -> List[Tool]:
    """获取所有工具"""
    return [
        Tool(
            name="hello",
            description="问候工具",
            func=hello_tool
        ),
        Tool(
            name="calculate",
            description="基本计算工具",
            func=calculate_tool
        )
    ]'''
    
    def get_fastmcp_resources_template(self) -> str:
        """获取FastMCP资源模板"""
        return '''"""FastMCP资源示例"""

from typing import List, Dict, Any
from fastmcp.resources import Resource
from loguru import logger

def get_status_resource() -> Dict[str, Any]:
    """获取服务器状态资源"""
    logger.info("获取服务器状态")
    return {
        "status": "running",
        "uptime": "00:05:23",
        "memory_usage": "45.2MB",
        "version": "1.0.0"
    }

def get_config_resource() -> Dict[str, Any]:
    """获取配置信息资源"""
    logger.info("获取配置信息")
    return {
        "server_name": "example-mcp-server",
        "log_level": "INFO",
        "max_connections": 100,
        "timeout": 30
    }

def get_resources() -> List[Resource]:
    """获取所有资源"""
    return [
        Resource(
            name="status",
            description="服务器状态信息",
            func=get_status_resource
        ),
        Resource(
            name="config",
            description="服务器配置信息",
            func=get_config_resource
        )
    ]'''
    
    def get_readme_template(self, config: Any) -> str:
        """获取README模板"""
        template_str = '''# {{ project_name_title }}

{{ description }}

## 快速开始

### 安装依赖

```bash
# 安装uv（如果尚未安装）
curl -LsSf https://astral.sh/uv/install.sh | sh

# 安装项目依赖
uv sync
```

### 运行应用

```bash
{% if project_type == "fastapi" %}
# 启动FastAPI服务
uv run uvicorn main:app --reload
{% elif project_type == "fastmcp" %}
# 运行FastMCP服务器
uv run python main.py
{% else %}
# 运行应用
uv run python main.py
{% endif %}
```

### Docker运行

```bash
# 构建Docker镜像
docker build -t {{ project_name }} .

# 运行容器
docker run -p 8000:8000 {{ project_name }}

# 或者使用docker-compose
docker-compose up -d
```

## 开发

### 代码质量

```bash
# 代码格式化
uv run black .

# 代码检查
uv run ruff check .

# 类型检查
uv run mypy .
```

### 测试

```bash
# 运行测试
uv run pytest

# 测试覆盖率
uv run pytest --cov=src
```

## 许可证

本项目采用 {{ license }} 许可证。'''
        
        template = Template(template_str)
        return template.render(config.get_template_context())
    
    def get_changelog_template(self) -> str:
        """获取变更日志模板"""
        return '''# Changelog

## [Unreleased]

### Added
- 项目初始化

## [0.1.0] - 2024-01-01

### Added
- 初始项目结构
- 基础功能实现'''
    
    def get_contributing_template(self) -> str:
        """获取贡献指南模板"""
        return '''# 贡献指南

感谢您对本项目的关注！我们欢迎各种形式的贡献。

## 如何贡献

### 提交代码

1. Fork 本项目
2. 创建功能分支 (`git checkout -b feature/AmazingFeature`)
3. 提交变更 (`git commit -m "Add some AmazingFeature"`)
4. 推送到分支 (`git push origin feature/AmazingFeature`)
5. 创建 Pull Request

### 开发环境设置

```bash
# 克隆项目
git clone https://github.com/your-username/your-repo.git
cd your-repo

# 安装依赖
uv sync --all-extras --dev
```'''
    
    def get_license_template(self) -> str:
        """获取许可证模板"""
        return '''MIT License

Copyright (c) 2024 Your Name

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.'''
    
    def get_docs_index_template(self, config: Any) -> str:
        """获取文档首页模板"""
        template_str = '''# {{ project_name_title }}

{{ description }}

## 概述

本项目是一个基于Python的{{ project_type }}应用。

## 主要特性

- 📦 使用uv进行依赖管理
- 🔧 预配置的开发工具
- 📝 完整的文档和代码注释
- 🧪 单元测试覆盖
- 🐳 Docker容器化支持

## 快速开始

请参考 [README.md](../README.md) 获取详细的安装和使用说明。'''
        
        template = Template(template_str)
        return template.render(config.get_template_context())
    
    def list_templates(self) -> List[str]:
        """列出可用模板"""
        return ["fastapi", "fastmcp"]
    
    def get_template_info(self, template_name: str) -> Dict[str, Any]:
        """获取模板信息"""
        templates_info = {
            "fastapi": {
                "name": "FastAPI项目",
                "description": "现代化的Web API项目模板",
                "dependencies": ["fastapi", "uvicorn", "loguru"]
            },
            "fastmcp": {
                "name": "FastMCP项目", 
                "description": "FastMCP服务器项目模板",
                "dependencies": ["fastmcp", "loguru", "rich"]
            }
        }
        
        return templates_info.get(template_name, {})
